

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Kaleidoscope: Kaleidoscope Introduction and the Lexer &#8212; LLVM 9 documentation</title>
    <link rel="stylesheet" href="../../_static/llvm-theme.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script src="../../_static/jquery.js"></script>
    <script src="../../_static/underscore.js"></script>
    <script src="../../_static/doctools.js"></script>
    <script src="../../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head><body>
<div class="logo">
  <a href="../../index.html">
    <img src="../../_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../genindex.html" title="General Index"
             accesskey="I">index</a></li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../../index.html">Documentation</a>&raquo;</li>

        <li class="nav-item nav-item-this"><a href="">Kaleidoscope: Kaleidoscope Introduction and the Lexer</a></li> 
      </ul>
    </div>


    <div class="document">
      <div class="documentwrapper">
          <div class="body" role="main">
            
  <div class="section" id="kaleidoscope-kaleidoscope-introduction-and-the-lexer">
<h1>Kaleidoscope: Kaleidoscope Introduction and the Lexer<a class="headerlink" href="#kaleidoscope-kaleidoscope-introduction-and-the-lexer" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><p><a class="reference internal" href="#the-kaleidoscope-language" id="id1">The Kaleidoscope Language</a></p></li>
<li><p><a class="reference internal" href="#the-lexer" id="id2">The Lexer</a></p></li>
</ul>
</div>
<div class="section" id="the-kaleidoscope-language">
<h2><a class="toc-backref" href="#id1">The Kaleidoscope Language</a><a class="headerlink" href="#the-kaleidoscope-language" title="Permalink to this headline">¶</a></h2>
<p>This tutorial is illustrated with a toy language called
“<a class="reference external" href="http://en.wikipedia.org/wiki/Kaleidoscope">Kaleidoscope</a>” (derived
from “meaning beautiful, form, and view”). Kaleidoscope is a procedural
language that allows you to define functions, use conditionals, math,
etc. Over the course of the tutorial, we’ll extend Kaleidoscope to
support the if/then/else construct, a for loop, user defined operators,
JIT compilation with a simple command line interface, debug info, etc.</p>
<p>We want to keep things simple, so the only datatype in Kaleidoscope
is a 64-bit floating point type (aka ‘double’ in C parlance). As such,
all values are implicitly double precision and the language doesn’t
require type declarations. This gives the language a very nice and
simple syntax. For example, the following simple example computes
<a class="reference external" href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers:</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Compute the x&#39;th fibonacci number.</span>
<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">3</span> <span class="n">then</span>
    <span class="mi">1</span>
  <span class="k">else</span>
    <span class="n">fib</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">+</span><span class="n">fib</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span>

<span class="c1"># This expression will compute the 40th number.</span>
<span class="n">fib</span><span class="p">(</span><span class="mi">40</span><span class="p">)</span>
</pre></div>
</div>
<p>We also allow Kaleidoscope to call into standard library functions - the
LLVM JIT makes this really easy. This means that you can use the
‘extern’ keyword to define a function before you use it (this is also
useful for mutually recursive functions).  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">extern</span> <span class="n">sin</span><span class="p">(</span><span class="n">arg</span><span class="p">);</span>
<span class="n">extern</span> <span class="n">cos</span><span class="p">(</span><span class="n">arg</span><span class="p">);</span>
<span class="n">extern</span> <span class="n">atan2</span><span class="p">(</span><span class="n">arg1</span> <span class="n">arg2</span><span class="p">);</span>

<span class="n">atan2</span><span class="p">(</span><span class="n">sin</span><span class="p">(</span><span class="o">.</span><span class="mi">4</span><span class="p">),</span> <span class="n">cos</span><span class="p">(</span><span class="mi">42</span><span class="p">))</span>
</pre></div>
</div>
<p>A more interesting example is included in Chapter 6 where we write a
little Kaleidoscope application that <a class="reference external" href="LangImpl06.html#kicking-the-tires">displays a Mandelbrot
Set</a> at various levels of magnification.</p>
<p>Let’s dive into the implementation of this language!</p>
</div>
<div class="section" id="the-lexer">
<h2><a class="toc-backref" href="#id2">The Lexer</a><a class="headerlink" href="#the-lexer" title="Permalink to this headline">¶</a></h2>
<p>When it comes to implementing a language, the first thing needed is the
ability to process a text file and recognize what it says. The
traditional way to do this is to use a
“<a class="reference external" href="http://en.wikipedia.org/wiki/Lexical_analysis">lexer</a>” (aka
‘scanner’) to break the input up into “tokens”. Each token returned by
the lexer includes a token code and potentially some metadata (e.g. the
numeric value of a number). First, we define the possibilities:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="c1">// The lexer returns tokens [0-255] if it is an unknown character, otherwise one</span>
<span class="c1">// of these for known things.</span>
<span class="k">enum</span> <span class="nc">Token</span> <span class="p">{</span>
  <span class="n">tok_eof</span> <span class="o">=</span> <span class="mi">-1</span><span class="p">,</span>

  <span class="c1">// commands</span>
  <span class="n">tok_def</span> <span class="o">=</span> <span class="mi">-2</span><span class="p">,</span>
  <span class="n">tok_extern</span> <span class="o">=</span> <span class="mi">-3</span><span class="p">,</span>

  <span class="c1">// primary</span>
  <span class="n">tok_identifier</span> <span class="o">=</span> <span class="mi">-4</span><span class="p">,</span>
  <span class="n">tok_number</span> <span class="o">=</span> <span class="mi">-5</span><span class="p">,</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdentifierStr</span><span class="p">;</span> <span class="c1">// Filled in if tok_identifier</span>
<span class="k">static</span> <span class="kt">double</span> <span class="n">NumVal</span><span class="p">;</span>             <span class="c1">// Filled in if tok_number</span>
</pre></div>
</div>
<p>Each token returned by our lexer will either be one of the Token enum
values or it will be an ‘unknown’ character like ‘+’, which is returned
as its ASCII value. If the current token is an identifier, the
<code class="docutils literal notranslate"><span class="pre">IdentifierStr</span></code> global variable holds the name of the identifier. If
the current token is a numeric literal (like 1.0), <code class="docutils literal notranslate"><span class="pre">NumVal</span></code> holds its
value. We use global variables for simplicity, but this is not the
best choice for a real language implementation :).</p>
<p>The actual implementation of the lexer is a single function named
<code class="docutils literal notranslate"><span class="pre">gettok</span></code>. The <code class="docutils literal notranslate"><span class="pre">gettok</span></code> function is called to return the next token
from standard input. Its definition starts as:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="c1">/// gettok - Return the next token from standard input.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="n">gettok</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">static</span> <span class="kt">int</span> <span class="n">LastChar</span> <span class="o">=</span> <span class="sc">&#39; &#39;</span><span class="p">;</span>

  <span class="c1">// Skip any whitespace.</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">isspace</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span>
    <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">gettok</span></code> works by calling the C <code class="docutils literal notranslate"><span class="pre">getchar()</span></code> function to read
characters one at a time from standard input. It eats them as it
recognizes them and stores the last character read, but not processed,
in LastChar. The first thing that it has to do is ignore whitespace
between tokens. This is accomplished with the loop above.</p>
<p>The next thing <code class="docutils literal notranslate"><span class="pre">gettok</span></code> needs to do is recognize identifiers and
specific keywords like “def”. Kaleidoscope does this with this simple
loop:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">isalpha</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span> <span class="p">{</span> <span class="c1">// identifier: [a-zA-Z][a-zA-Z0-9]*</span>
  <span class="n">IdentifierStr</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">isalnum</span><span class="p">((</span><span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">())))</span>
    <span class="n">IdentifierStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;def&quot;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tok_def</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;extern&quot;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tok_extern</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">tok_identifier</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that this code sets the ‘<code class="docutils literal notranslate"><span class="pre">IdentifierStr</span></code>’ global whenever it
lexes an identifier. Also, since language keywords are matched by the
same loop, we handle them here inline. Numeric values are similar:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">)</span> <span class="p">{</span>   <span class="c1">// Number: [0-9.]+</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">NumStr</span><span class="p">;</span>
  <span class="k">do</span> <span class="p">{</span>
    <span class="n">NumStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>
    <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
  <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">);</span>

  <span class="n">NumVal</span> <span class="o">=</span> <span class="n">strtod</span><span class="p">(</span><span class="n">NumStr</span><span class="p">.</span><span class="n">c_str</span><span class="p">(),</span> <span class="mi">0</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">tok_number</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This is all pretty straightforward code for processing input. When
reading a numeric value from input, we use the C <code class="docutils literal notranslate"><span class="pre">strtod</span></code> function to
convert it to a numeric value that we store in <code class="docutils literal notranslate"><span class="pre">NumVal</span></code>. Note that
this isn’t doing sufficient error checking: it will incorrectly read
“1.23.45.67” and handle it as if you typed in “1.23”. Feel free to
extend it!  Next we handle comments:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;#&#39;</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Comment until end of line.</span>
  <span class="k">do</span>
    <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\n&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\r&#39;</span><span class="p">);</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">gettok</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
</div>
<p>We handle comments by skipping to the end of the line and then return
the next token. Finally, if the input doesn’t match one of the above
cases, it is either an operator character like ‘+’ or the end of the
file. These are handled with this code:</p>
<div class="highlight-c++ notranslate"><div class="highlight"><pre><span></span>  <span class="c1">// Check for end of file.  Don&#39;t eat the EOF.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="n">EOF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tok_eof</span><span class="p">;</span>

  <span class="c1">// Otherwise, just return the character as its ascii value.</span>
  <span class="kt">int</span> <span class="n">ThisChar</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
  <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
  <span class="k">return</span> <span class="n">ThisChar</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>With this, we have the complete lexer for the basic Kaleidoscope
language (the <a class="reference external" href="LangImpl02.html#full-code-listing">full code listing</a> for the Lexer
is available in the <a class="reference external" href="LangImpl02.html">next chapter</a> of the tutorial).
Next we’ll <a class="reference external" href="LangImpl02.html">build a simple parser that uses this to build an Abstract
Syntax Tree</a>. When we have that, we’ll include a
driver so that you can use the lexer and parser together.</p>
<p><a class="reference external" href="LangImpl02.html">Next: Implementing a Parser and AST</a></p>
</div>
</div>


            <div class="clearer"></div>
          </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../genindex.html" title="General Index"
             >index</a></li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../../index.html">Documentation</a>&raquo;</li>

        <li class="nav-item nav-item-this"><a href="">Kaleidoscope: Kaleidoscope Introduction and the Lexer</a></li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2003-2020, LLVM Project.
      Last updated on 2020-09-20.
      Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
    </div>
  </body>
</html>